package com.awanp3.nimbus.system.strategy.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.collection.CollUtil;
import com.awanp3.nimbus.common.core.constant.HeaderConstants;
import com.awanp3.nimbus.system.domain.vo.*;
import com.awanp3.nimbus.system.form.SocialLoginBody;
import com.awanp3.nimbus.system.service.ISysSocialService;
import com.awanp3.nimbus.system.service.ISysUserService;
import com.awanp3.nimbus.system.strategy.SysLoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import com.awanp3.nimbus.system.strategy.IAuthStrategy;
import com.awanp3.nimbus.common.core.exception.ServiceException;
import com.awanp3.nimbus.common.core.utils.StreamUtils;
import com.awanp3.nimbus.common.core.utils.ValidatorUtils;
import com.awanp3.nimbus.common.json.utils.JsonUtils;
import com.awanp3.nimbus.common.satoken.utils.LoginHelper;
import com.awanp3.nimbus.common.social.config.properties.SocialProperties;
import com.awanp3.nimbus.common.social.utils.SocialUtils;
import com.awanp3.nimbus.common.tenant.helper.TenantHelper;
import com.awanp3.nimbus.system.api.model.LoginUser;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 第三方授权策略
 *
 * @author nimbus
 */
@Slf4j
@Service("social" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class SocialAuthStrategy implements IAuthStrategy {

    private final SocialProperties socialProperties;

    private final SysLoginService loginService;

    private final ISysSocialService sysSocialService;

    private final ISysUserService sysUserService;

    /**
     * 登录-第三方授权登录
     *
     * @param body     登录信息
     */
    @Override
    public LoginVo login(String body) {
        SocialLoginBody loginBody = JsonUtils.parseObject(body, SocialLoginBody.class);
        ValidatorUtils.validate(loginBody);

        SysClientVo client = loginService.checkClient(loginBody.getClientId(), loginBody.getGrantType());

        if (TenantHelper.isEnable()){
            loginService.checkTenant(loginBody.getTenantId());
        }

        AuthResponse<AuthUser> response = SocialUtils.loginAuth(
            loginBody.getSource(), loginBody.getSocialCode(),
            loginBody.getSocialState(), socialProperties);
        if (!response.ok()) {
            throw new ServiceException(response.getMsg());
        }
        AuthUser authUserData = response.getData();
        List<SysSocialVo> list = sysSocialService.selectByAuthId(authUserData.getSource() + authUserData.getUuid());
        if (CollUtil.isEmpty(list)) {
            throw new ServiceException("你还没有绑定第三方账号，绑定后才可以登录！");
        }
        SysSocialVo socialVo;
        if (TenantHelper.isEnable()) {
            Optional<SysSocialVo> opt = StreamUtils.findAny(list, x -> x.getTenantId().equals(loginBody.getTenantId()));
            if (opt.isEmpty()) {
                throw new ServiceException("对不起，你没有权限登录当前租户！");
            }
            socialVo = opt.get();
        } else {
            socialVo = list.get(0);
        }
        SysUserVo sysUserVo = sysUserService.selectUserById(socialVo.getUserId());
        LoginUser loginUser = loginService.buildLoginUser(sysUserVo);
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());

        SaLoginParameter model = new SaLoginParameter();
        model.setDeviceType(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(HeaderConstants.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());
        return loginVo;
    }

}
